package ac2.util.serial;

import msg.AC2Messages;
import ac2.Global;
import ac2.util.serial.packets.*;

public class PacketFactory {

	/**
	 * Creates a packet from a command and its arguments.
	 * @param command The command string
	 * @param argument The arguments for the command
	 * @param target The target node of this command
	 * @return The packet for the specified command
	 */
	public static IBytePacket Create(String command, String argument, String target)
	{
		IBytePacket packet = null;
		
		System.out.println("Command is: " + command);
		
		if (command.equals("UPDATE_TEMP"))
		{
			double temperature = Double.parseDouble(argument);
			byte targetNode = Byte.parseByte(target);
			
			packet = new SetTemperaturePacket(temperature, targetNode);
			
			System.out.println("Packet is " + packet.toString());
		}
		
		else if (command.equals("REQUEST_ZONE_STATUS"))
		{
			byte targetNode = Byte.parseByte(target);
			packet = new RequestStatusPacket(targetNode);
		}
		
		else if (command.equals("SET_MODE"))
		{
			byte targetNode = Byte.parseByte(target);
			byte mode = Byte.parseByte(argument);
			
			packet = new SetModePacket(targetNode, mode);
		}
		
		return packet;
	}
	
	public static IBytePacket Create(byte[] packetBytes)
	{
		IBytePacket packet = null;
		
		try
		{
			Global.Debug("MODE IS " + packetBytes[10]);
			
			// The 10th byte is the message id
			switch(packetBytes[10])
			{
			case AC2Messages.FUNCTION_TEMPERATURE_UPDATE:
				Global.Debug("Creating new TemperatureUpdatePacket");
				packet = new TemperatureUpdatePacket(packetBytes);
				break;
			case AC2Messages.FUNCTION_SET_TARGET_TEMPERATURE:
				//packet = new SetTemperaturePacket(packetBytes);
				Global.Error("FUNCTION_SET_TARGET_TEMPERATURE not valid for incoming packets");
				break;
			case AC2Messages.FUNCTION_SET_MODE:
				//packet = new SetModePacket(packetBytes);
				Global.Error("FUNCTION_SET_MODE not valid for incoming packets");
				break;
			case AC2Messages.FUNCTION_VENT_STATUS_UPDATE:
				Global.Debug("Creating new VentStatusUpdatePacket");
				packet = new VentStatusUpdatePacket(packetBytes);
				break;
			case AC2Messages.FUNCTION_REQUEST_VENT_STATUS:
				//packet = new RequestStatusPacket(packetBytes);
				Global.Error("FUNCTION_REQUEST_VENT_STATUS not valid for incoming packets");
				break;
			}
		}
		catch (Exception ex)
		{
			System.out.println(ex.toString());
		}
		
		if (packet != null) packet.init();
		
		return packet;
	}
	
}
